package system;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class ScoreHandler {
	static String ip;
	static int port = 25401;

	final static int ENTRIES = 10;
	public static String[] names;
	public static String[] scores;

	public static void writeScore(String name, String score){

		try {			
			// connect to server
			Socket s = new Socket(ip, port);
			OutputStream out = s.getOutputStream();
			InputStream in = s.getInputStream();
			PrintStream pout = new PrintStream(out);

			// write data to server
			pout.println(name);
			pout.println(score);

			// close connection
			pout.close();
			in.close();
			s.close();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	public static boolean readScore(){
		Socket socket;
		try {
			socket = new Socket(ip, port+1);
			BufferedReader fromServer = null;
			fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			// store the entries from the server into static arrays
			names = new String[ENTRIES];
			scores = new String[ENTRIES];
			for (int i = 0; i < ENTRIES; i++){
				String returned = fromServer.readLine();
				String[] result = returned.split("\\s");
				if(result.length == 2){
					names[i] = result[0];
					scores[i] = result[1];
				}
			}
			return true;

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static void readIP(){
		// get IP from input file
		try {
			FileInputStream fstream = new FileInputStream("data/game/server-ip.dat");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			ip = br.readLine();
			in.close();
			br.close();
			System.out.println(ip);
		} catch (Exception e){
			System.out.println("Error reading server-ip.dat");
		}
	}

}
